import 'package:get/get.dart';
import 'package:ride_rex/net/common_global_url.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ride_rex/net/common_net_builder.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/service/config_service.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:ride_rex/ui/common_dialogs.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../constant.dart';
import '../service/log_service.dart';

class ApiLogin extends CommonApi {
  ApiLogin.login({
    required int oauthType,
    required String token,
  }) : super(CommonGlobalUrl.login, params: {'oauthType': oauthType, 'token': token});

  ApiLogin.logout() : super(CommonGlobalUrl.logout);
}

class LoginLogic extends GetxController with OnceClick {
  bool agree = false;

  ///fastLogin
  Future fastLogin() async {
    if (!agree) {
      CommonDialogs.showPrivacy(
        onConfirm: () {
          agree = true;
          update();
          _login(oauthType: 4, token: DeviceInfoUtils().deviceId);
        },
      );
      return;
    }

    _login(oauthType: 4, token: DeviceInfoUtils().deviceId);
    LMLogManager.stat(page: 'quicklogin');
  }

  Future _login({required int oauthType, required String token}) async {
    startOnce(() async {
      dynamic json = await ApiLogin.login(oauthType: oauthType, token: token)
          .post(contentType: 'application/x-www-form-urlencoded')
          .whenComplete(Loading.dismiss);

      if (json is Map) {
        ///保存用户信息
        UserService.instance.setUserInfo(json['userInfo']);

        ///保存userId
        await CommonStorage().setString(StorageKey.spKeyUserId, json['userInfo']['userId']);

        ///保存token
        if (json['token'] is String) {
          await CommonStorage().setString(StorageKey.spKeyToken, json['token']);

          ///刷新请求头
          await CommonNet.refreshHeader();

          ///获取融云token
          getRongCloudToken();

          ///打开MainPage
          CommonRoute.openMain();

          LMLogManager.stat(page: 'loginsuccess');
        }
      }
    });
  }

  ///appleLogin
  Future appleLogin() async {
    if (!agree) {
      CommonDialogs.showPrivacy(
        onConfirm: () async {
          agree = true;
          update();
          String token = await _getAppleIdentityToken();
          if (token.empty) return;
          _login(oauthType: 3, token: token);
        },
      );
      return;
    }

    _login(oauthType: 3, token: await _getAppleIdentityToken());
    LMLogManager.stat(page: 'applelogin');
  }

  Future<String> _getAppleIdentityToken() async {
    Loading.show();
    try {
      var credential = await SignInWithApple.getAppleIDCredential(scopes: []);
      await Future.delayed(const Duration(milliseconds: 500));
      Loading.dismiss();
      return credential.identityToken ?? '';
    } catch (e) {
      Loading.dismiss();
      return '';
    }
  }

  ///获取融云token
  Future getRongCloudToken() async {
    dynamic json = await ApiConfig.rongCloud().get();
    if (json is String) {
      ///获取融云token成功，连接融云服务器
    }
  }
}

class LogoutLogic {
  ///退出登录
  static Future logout() async {
    clear();
    await ApiLogin.logout().post();
  }

  static void clear() {
    CommonStorage().remove(StorageKey.spKeyToken);
    CommonStorage().remove(StorageKey.spKeyUserId);
  }
}
